<template>
  <basic-container class="sms" v-loading="loading" element-loading-text="数据加载中...">
    <dataList
      ref="sms"
      hideFilterBtn
      openIndex
      operaColumnWidth="120"
      :pageInfo="pager"
      :listData="tableData"
      :dataInfo="dataInfo"
      :operaInfo="operaInfo"
      :menuList="menuList"
      :listLayout="['menu','filter']"
      :filterList="filterList"
      @btn-click="handleBtnClick"
      @menu-click="handleMenuClick"
    ></dataList>
    <v-dialog :show.sync="dialogVisible" width="1000px" v-loading="dialogLoading" element-loading-text="正在保存..." :title="isLook ? '短信信息详情' : isEdit ? '编辑' : '新增'" @beforeClose="beforeClose">
      <el-form ref="assessInfoData" :model="assessInfoData" label-width="80px" :rules="assessInfoData_rules">
        <el-form-item label="短信类型" prop="smsType" v-if="isEdit || isLook">
          <el-select clearable placeholder="请选择短信类型" v-model="assessInfoData.smsType" v-if="!isLook">
            <el-option v-for="item in smsTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <span class="in_txt" v-if="isLook">{{getInit(assessInfoData.smsType,smsTypeList)}}</span>
        </el-form-item>
        <el-form-item label="接收人" prop="receiveName">
          <el-input v-halfCharCode v-model="assessInfoData.receiveName" placeholder="请输入接收人" v-if="!isLook" />
          <span class="in_txt" v-if="isLook">{{assessInfoData.receiveName}}</span>
        </el-form-item>
        <el-form-item label="手机号" prop="receiveMobile">
          <el-input v-halfCharCode v-model="assessInfoData.receiveMobile" placeholder="请输入手机号" v-if="!isLook" />
          <span class="in_txt" v-if="isLook">{{assessInfoData.receiveMobile}}</span>
        </el-form-item>
        <el-form-item label="短信内容" prop="smsContent">
          <el-input v-halfCharCode type="textarea" v-model="assessInfoData.smsContent" placeholder="请输入短信内容" v-if="!isLook" />
          <span class="in_txt" v-if="isLook">{{assessInfoData.smsContent}}</span>
        </el-form-item>
        <el-form-item label="发送时间" prop="sendTime">
          <el-date-picker v-if="!isLook" v-model="assessInfoData.sendTime" type="datetime" placeholder="请选择发送时间" format="yyyy-MM-dd HH:mm:ss" valueFormat="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          <span class="in_txt" v-if="isLook">{{assessInfoData.sendTime}}</span>
        </el-form-item>
        <el-form-item label="短信状态" prop="smsStatus" v-if="isEdit || isLook">
          <el-select clearable placeholder="请选择短信状态" v-model="assessInfoData.smsStatus" v-if="!isLook">
            <el-option v-for="item in smsStatusList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <span class="in_txt" v-if="isLook">{{getInit(assessInfoData.smsStatus,smsStatusList)}}</span>
        </el-form-item>
      </el-form>
      <span slot="foot" v-if="!isLook">
        <el-button v-throttle="[commit]">{{isEdit ? '修 改' : '保 存'}}</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </span>
    </v-dialog>
  </basic-container>
</template>

<script>
import { fetchList, addObj, putObj, delObj, getObj } from '~/admin/api/note'
import { validatePhone } from '~/utils/validate.js'
export default {
  name: "sms",
  provide () {
    return {
      initList: this.getListData
    };
  },
  beforeMount () {
    this.getListData()
    this.smsTypeList = this.getDict('sms_type')
    this.smsStatusList = this.getDict('smsSStatus')
  },
  data () {
    return {
      tableData: [],
      // 请求参数
      params: {
        current: 1,
        size: 10
      },
      // 分页
      pager: {
        total: 0, // 总页数
        current: 1, // 当前页数
        size: 10 // 每页显示多少条
      },
      filterList: [
        { label: '接收人', inputType: 'input', name: 'receiveName', placeholder: '请输入接收人', defaultValue: '' },
        { label: '手机号', inputType: 'input', name: 'receiveMobile', placeholder: '请输入手机号', defaultValue: '' },
        { label: '发送状态', inputType: 'dict', dictName: 'smsSStatus', name: 'smsStatus', placeholder: '请选择发送状态', defaultValue: '' },
        //{ label: '发送开始时间', inputType: 'date', name: 'start', placeholder: '请选择发送开始时间', defaultValue: '' },
        //{ label: '发送结束时间', inputType: 'date', name: 'end', placeholder: '请选择发送结束时间', defaultValue: '' },
				{ label: '发送时间', inputType: 'daterange', name: ['start','end'],  defaultValue: ['',''] }
      ],
      // 页面loading
      loading: false,
      // 弹窗
      dialogLoading: false,
      dialogVisible: false,
      isEdit: false,
      isLook: false,
      assessInfoData: {
        smsType: '',
        receiveName: '',
        receiveMobile: '',
        smsContent: '',
        sendTime: '',
        smsStatus: ''
      },
      assessInfoData_rules: {
        receiveName: [{ required: true, message: '请输入接收人', trigger: 'blur' },
        { min: 2, max: 1200, message: '长度在 2 到 1200 个字符', trigger: 'blur' }],
        receiveMobile: [{ required: true, message: '请输入手机号', trigger: 'blur' },
        { min: 2, max: 1200, message: '长度在 2 到 1200 个字符', trigger: 'blur' },
        { validator: validatePhone, trigger: "blur" }],
        smsContent: [{ required: true, message: '请输入短信内容', trigger: 'blur' },
        { min: 2, max: 225, message: '长度在 2 到 225 个字符', trigger: 'blur' }],
      },
      // 字典
      smsTypeList: [],
      smsStatusList: []
    }
  },
  computed: {
    //权限
    permissionList (scope) {
      return {
        editBtn: this.getPermissions('sms_edit'),
        delBtn: this.getPermissions('sms_del'),
        getBtn: this.getPermissions('sms_get')
      }
    },
    // 头部按钮
    menuList () {
      return this.getPermissions('sms_edit') ? ['add'] : []
    },
    //数据表头
    dataInfo () {
      return [
        { label: '短信类型', prop: 'smsType', formatter: this.initSmsType, width: '120' },
        { label: '接收人', prop: 'receiveName', width: '150', 'show-overflow-tooltip': true },
        { label: '手机号', prop: 'receiveMobile', width: '150' },
        { label: '短信内容', prop: 'smsContent', width: '400', 'show-overflow-tooltip': true },
        { label: '发送状态', prop: 'smsStatus', formatter: this.initSmsStatus, width: '120' },
        { label: '发送时间', prop: 'sendTime', width: '180' }
      ]
    },
    //操作按钮
    operaInfo () {
      return [
        { label: '编辑', name: 'edit', verify: () => this.permissionList.editBtn },
        { label: '删除', name: 'del', verify: () => this.permissionList.delBtn },
        { label: '重新发送', name: 'againSend', verify: row => row.smsStatus === '9' || row.smsStatus === '2' },
        { label: '取消', name: 'cancel', verify: row => row.smsStatus === '9' || row.smsStatus === '0' },
        { label: '查看', name: 'look', verify: () => this.permissionList.getBtn }
      ]
    }
  },
  methods: {
    // 获取列表
    getListData (params = {}) {
      this.loading = true;
      let requestData = { ...this.params, ...params };
      let obj = {}
      for (let key in requestData) {
        if ((requestData[key] === 0 || requestData[key]) && requestData[key].toString().replace(/(^\s*)|(\s*$)/g, '') !== '') {
          obj[key] = requestData[key]
        }
      }
      requestData = obj
      fetchList(requestData)
        .then(res => {
          const { total, current, size, records } = res.data.data;
          this.tableData = records;
          this.params = requestData;
          this.pager = { total, current, size };
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 菜单点击监听
    handleMenuClick (type) {
      switch (type) {
        case "add":
          this.handleSave();
          break;
        default:
          this.$message(type);
          break;
      }
    },
    // 按钮点击监听
    handleBtnClick ({ type, row }) {
      switch (type) {
        case 'edit':
          this.handleUpdate(row)
          break;
        case 'del':
          this.rowDel(row)
          break;
        case 'againSend':
          this.againSend(row)
          break;
        case 'cancel':
          this.cancel(row)
          break;
        case 'look':
          this.getLook(row)
          break;
        default:
          break
      }
    },
    // 短信类型初始化
    initSmsType (row, column, cellValue) {
      let obj = this.smsTypeList.find(it => it.value === cellValue);
      if (obj) {
        return obj.label
      }
      return ''
    },
    //发送状态初始化
    initSmsStatus (row, column, cellValue) {
      let obj = this.smsStatusList.find(it => it.value === cellValue);
      if (obj) {
        return obj.label
      }
      return ''
    },
    // 新增
    handleSave () {
      this.dialogVisible = true
    },
    //修改
    handleUpdate (row) {
      this.getDialog(row.smsId)
      this.isEdit = true
    },
    //删除
    rowDel: function (row, index) {
      this.$confirm('是否确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.smsId)
      }).then(data => {
        this.$message.success('删除成功')
        this.getListData({ current: 1 })
      })
    },
    // 重新发送
    againSend (row) {
      row.smsStatus = '2'
      this.$confirm('是否重新发送?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return putObj(row)
      }).then(data => {
        this.$message.success('发送成功')
        this.getListData({ current: 1 })
      })
    },
    // 取消
    cancel (row) {
      row.smsStatus = '0'
      putObj(row).then(response => {
        this.$message.success('修改成功')
        this.getListData({ current: 1 })
      }).catch(() => {
        this.$message.success('修改失败')
      })
    },
    // 查看
    getLook (row) {
      this.getDialog(row.smsId)
      this.isLook = true
    },
    // 新增修改弹框确定
    commit () {
      this.$refs.assessInfoData.validate(valid => {
        if (valid) {
          this.dialogLoading = true
          if (this.isEdit) {
            putObj(this.assessInfoData).then(res => {
              if (res.data.code === 0) {
                this.$notify.success('修改成功')
                this.dialogLoading = false
                this.handleCancel()
              } else {
                this.$notify.error('修改失败')
                this.dialogLoading = false
                this.handleCancel()
              }
            }).catch(() => {
              this.dialogLoading = false
            })
          } else {
            addObj(this.assessInfoData).then(res => {
              if (res.data.code === 0) {
                this.$notify.success('添加成功')
                this.dialogLoading = false
                this.handleCancel()
              } else {
                this.$notify.error('添加失败')
                this.dialogLoading = false
                this.handleCancel()
              }
            }).catch(() => {
              this.dialogLoading = false
            })
          }
        }
      })
    },
    // 新增修改弹框取消
    handleCancel () {
      this.assessInfoData = {}
      this.isEdit = false
      this.isLook = false
      this.dialogVisible = false
      this.getListData()
    },
    beforeClose () {
      this.handleCancel()
    },
    //获取弹框数据
    getDialog (id) {
      getObj(id).then(res => {
        if (res.data.code === 0) {
          this.assessInfoData = res.data.data
          this.dialogVisible = true
        }
      })
    },
    // 查看字典数据初始化
    getInit (num, sum) {
      let str = sum.find(it => it.value === num)
      if (str) {
        return str.label
      }
      return ''
    }
  }
}
</script>

<style scoped lang="scss">
.sms {
  .in_txt {
    color: #999;
  }
}
</style>
